package com.learn.learnsystem.controller.login;

import com.learn.learnsystem.entity.login.LoginUser;
import com.learn.learnsystem.utils.JwtTokenUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Tag(name = "用户管理", description = "用户相关操作接口")
public class LoginController {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    private final UserDetailsService userDetailsService;

    public LoginController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userDetailsService = userDetailsService;
    }

    @Operation(
            summary = "获取用户列表",
            description = "分页查询所有用户",
            parameters = {
                    @Parameter(name = "page", description = "页码", example = "1"),
                    @Parameter(name = "size", description = "每页数量", example = "10")
            }
    )
    @GetMapping("/query")
    public List<String> getUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        return List.of("User1", "User2");
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(@RequestBody LoginUser request, HttpServletResponse response) {
        // 执行认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        request.getUsername(),
                        request.getPassword()
                )
        );

        // 生成 JWT
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetails);
        String refreshToken = jwtTokenUtil.generateRefreshToken(userDetails);

        // 设置Refresh Token到HttpOnly Cookie
        ResponseCookie refreshCookie = ResponseCookie.from("refreshToken", refreshToken)
                .httpOnly(true)
                .secure(true) // 生产环境启用
                .sameSite("Lax")
                .maxAge(jwtTokenUtil.getRefreshExpiration())
                .path("/api/auth/refresh") // 只有这个路径才会携带cookie
                .build();

        response.addHeader(HttpHeaders.SET_COOKIE, refreshCookie.toString());

        // 返回响应
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put("token", token);
        responseMap.put("username", userDetails.getUsername());
        responseMap.put("expiresIn", String.valueOf(jwtTokenUtil.getAccessExpiration() / 1000));

        return ResponseEntity.ok(responseMap);
    }

    @PostMapping("/refresh")
    public ResponseEntity<?> refreshToken(HttpServletRequest request) {
        // 从Cookie获取Refresh Token
        String refreshToken = Arrays.stream(request.getCookies())
                .filter(c -> "refreshToken".equals(c.getName()))
                .findFirst()
                .map(Cookie::getValue)
                .orElseThrow(() -> new RuntimeException("Refresh token not found"));

        if (jwtTokenUtil.validateToken(refreshToken)) {
            String username = jwtTokenUtil.getUsernameFromToken(refreshToken);
            UserDetails user = userDetailsService.loadUserByUsername(username);
            String newAccessToken = jwtTokenUtil.generateToken(user);
            return ResponseEntity.ok()
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + newAccessToken)
                    .build();
        }
        return ResponseEntity.status(401).body("Invalid refresh token");
    }

    @GetMapping("/test")
    public String test() {
        return "test";
    }
}
